﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CountDown : MonoBehaviour, ICountDown {
    /// <summary>
    /// 开始计时回调
    /// </summary>
    /// <value></value>
    public Action OnCountDownStart { get; set; }
    /// <summary>
    /// 计时结束回调
    /// </summary>
    /// <value></value>
    public Action OnCountDownEnd { get; set; }
    /// <summary>
    /// 计时暂停回调
    /// </summary>
    /// <value></value>
    public Action OnCountDownPause { get; set; }
    /// <summary>
    /// 计时过程回调
    /// </summary>
    /// <value>int分别代表分钟数和秒钟数</value>
    public Action<int, int> OnCountDowning { get; set; }

    [SerializeField][Header ("分钟")]
    private int minutes = 0;
    [SerializeField][Header ("秒钟")]
    private int seconds = 0;

    [SerializeField]
    private bool pause = false;
    /// <summary>
    /// 暂停当前倒计时
    /// </summary>
    public bool Pause {
        get { return pause; }
        set {
            pause = value;
            if (OnCountDownEnd != null) {
                OnCountDownEnd ();
                Debug.Log ("时间暂停");
            }
        }
    }
    /// <summary>
    /// 当前秒钟数
    /// </summary>
    /// <value></value>
    public int currentSecond { get; private set; }
    /// <summary>
    /// 当前分钟数
    /// </summary>
    /// <value></value>
    public int currentMinute { get; private set; } //代表当前分钟数
    public void StartCountDown () {
        StartCoroutine ("StartCountDownIenumator");
    }
    public void StopCountDown () {
        StopCoroutine ("StartCountDownIenumator");
    }
    private IEnumerator StartCountDownIenumator () {
        int minute = minutes;
        int second = seconds;

        pause = false;

        Debug.Log ("倒计时开始");

        if (OnCountDownStart != null) {
        OnCountDownStart ();
        Debug.Log ("倒计时开始");
        }
        do {
            currentMinute = minute;
            do {
                while (pause) {
                    Debug.Log ("时间暂停");
                    yield return null;
                }
                second--;
                if (OnCountDowning != null) {
                    OnCountDowning (minute, second);
                }
                yield return new WaitForSeconds (1);
            } while (second > 0);
            second = 60;
            minute--;
        } while (minute >= 0);
        Debug.Log ("倒计时结束");

        if (OnCountDownEnd != null) {
            OnCountDownEnd ();
            Debug.Log ("倒计时结束");
        }
    }
}
public interface ICountDown {
    void StartCountDown ();
    void StopCountDown ();
    Action OnCountDownStart { get; set; }
    Action OnCountDownEnd { get; set; }
    Action OnCountDownPause { get; set; }
    Action<int, int> OnCountDowning { get; set; }
    bool Pause { get; set; }
}